﻿using System;
using System.Data.OleDb;
using System.IO;

namespace FlatFileReader
{
    class FlatFileReader
    {
        static void Main(string[] args)
        {
            var ioFile = Environment.CurrentDirectory + "\\testFile.txt";
            var fileName = Path.GetFileName(ioFile);
            var dir = Path.GetDirectoryName(ioFile);
            var connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + dir + "\\;Extended Properties=\"text;HDR=Yes;FMT=Delimited\"";

            Console.WriteLine(connectionString);

                var connReference = new OleDbConnection
                                                    {
                                                        ConnectionString = connectionString
                                                    };
            if(Directory.Exists(connReference.DataSource))
            {
                Console.WriteLine("DataSource Location Checks Out!");
                var objF = "SELECT * FROM ["+ fileName +"]";
                var cmd = new OleDbCommand(objF, connReference);
                try
                {
                    connReference.Open();
                    var reader = cmd.ExecuteReader();
                    if (reader != null)
                        if (reader.HasRows)
                        {
                            while(reader.Read())
                            {
                                Console.WriteLine(reader[0].ToString());
                                Console.WriteLine(reader[1].ToString());
                            }
                        }
                }
                catch (Exception exception)
                {
                    Console.WriteLine(exception.Message);

                    throw;
                }
                finally
                {
                    connReference.Close();
                    cmd.Dispose();
                }
                connReference.Close();
            }
            else
            {
                Console.WriteLine("This is obviously not your cup of tea. Study some more and try again later.");
            }

        }
    }
}
